#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash bwa-0.7.17.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules libatomic 

cd "$buildpath"
wget -t 20 -c https://github.com/lh3/bwa/archive/refs/tags/v0.7.17.tar.gz
wget -t 20 -c https://github.com/DLTcollab/sse2neon/archive/refs/heads/master.zip
tar xf v0.7.17.tar.gz && rm -rf v0.7.17.tar.gz
unzip master.zip && rm -rf master.zip
cp sse2neon-master/sse2neon.h bwa-0.7.17

cd bwa-0.7.17
sed -i "s/gcc/clang/" Makefile
sed -i "29c #include \"sse2neon.h\"" ksw.c
sed -i "33c extern const uint8_t rle_auxtab[8];" rle.h

make -j$(nproc)
mkdir -p "$installpath"/bwa-0.7.17
cp -a ./* "$installpath"/bwa-0.7.17

cat>"$installpath/bwa-0.7.17/bwa_modulefiles"<<EOF
#%Module1.0
conflict bwa
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set BWA \$pwd
setenv BWA \$BWA
prepend-path PATH \$BWA
EOF

rm -rf "$buildpath"/bwa-0.7.17
